import time
from random import randint
from PyQt5.QtWidgets import QHBoxLayout
from typing import List, Union, Tuple
import pyqtgraph as pg
from qtpy.QtWidgets import QVBoxLayout, QWidget
from pmgwidgets.widgets.basic.plots.pyqtgraph.base.pgplot import PMGPyQtGraphWidget
from pmgwidgets import color_str2tup


def convert_time(time_stamp: Union[float, int]):
    return time.strftime('%H:%M:%S', time.localtime(time_stamp))


class TimeSeriesPGWidget(PMGPyQtGraphWidget):
    """
    性能很好的监视面板，300个点每分钟刷新一次，可以保持
    """

    def __init__(self, parent=None):
        super().__init__(parent)

        self.plot_widget = pg.PlotWidget(self, axisItems={'bottom': pg.DateAxisItem()})
        self.legend = self.plot_widget.addLegend()
        self.v_layout.addWidget(self.plot_widget)
        # self.setMinimumSize(300, 200)
        # self.setMaximumSize(450, 300)
        self.xlabel: str = ''
        self.ylabel: str = ''
        self.threshold_line: float = 57
        self.y_range: Tuple[float, float] = None
        self.title: str = ''
        self.ticks = 5
        self.show_data_num = 10
        self.max_data = 200
        self.timestamp_list = []
        self.value_list = []
        self.repaint_all = False

    def show_time_series(self, timestamps: List[float], values: List[List[float]], tags=None):
        self.clear()
        for value_list in values:
            if value_list is not None:
                assert len(timestamps) == len(value_list)
        if tags is not None:
            assert len(tags) == len(values)
        else:
            tags = [i + 1 for i in range(len(values))]

        self.plot(timestamps, values, tags)

    def plot(self, x, ylist, tags: List = None):

        y = [self.threshold_line for i in x]
        if len(ylist) + 1 != len(self.lines):
            if tags is None:
                tags = [None] * len(ylist)
            l = self.plot_widget.plot(x, y, pen='#ff00ff')
            for line in self.lines:
                line.clear()
            self.lines = []
            self.plot_widget.setYRange(*self.y_range)
            self.legend.clear()
            self.lines.append(l)
            assert len(self._symbols) >= len(ylist), 'Too much lines to monitor!'
            for i, y in enumerate(ylist):
                plot_data = self.plot_widget.plot(x, y, **self._symbols[i], name=tags[i])
                self.lines.append(plot_data)
        else:
            self.lines[0].setData(x, y)
            for i, y in enumerate(ylist):
                self.lines[i + 1].setData(x, y)


class PMGTimeSeriesPlot(QWidget):
    def __init__(self, parent: QWidget = None):
        super(PMGTimeSeriesPlot, self).__init__(parent)

        layout = QHBoxLayout()
        self.setLayout(layout)
        self.control_layout = QVBoxLayout()
        layout.addLayout(self.control_layout)
        self.time_series = TimeSeriesPGWidget()
        layout.addWidget(self.time_series)

    def set_data(self, timestamps: List[float], values: List[List[float]], tags: List[str] = None):
        self.time_series.show_time_series(timestamps, values, tags)

    def insert_data(self, timestamp: float, values: List[float], tags: List[float]):
        raise NotImplementedError
        self.time_series.insert_data(timestamp, values)

    def config_chart_text(self, title: str, xlabel: str, ylabel: str):
        self.time_series.title = title
        self.time_series.xlabel = xlabel
        self.time_series.ylabel = ylabel

    def alert(self, alert_level: int):
        if alert_level == 1:
            self.time_series.face_color = '#dc321e'
        elif alert_level == 2:
            self.time_series.face_color = '#c86428'
        else:
            self.time_series.face_color = '#ffffff'


if __name__ == '__main__':
    import sys
    from qtpy.QtWidgets import QApplication
    from qtpy.QtCore import QTimer

    app = QApplication(sys.argv)
    pmqt5mplwgt = PMGTimeSeriesPlot()
    pmqt5mplwgt.time_series.line_color = '#ff0000'
    pmqt5mplwgt.time_series.border_color = '#ff0000'
    pmqt5mplwgt.time_series.symbol = '圆'
    pmqt5mplwgt.time_series.y_range = (0, 100)
    pmqt5mplwgt.time_series.threshold_line = 0.8 * 100
    pmqt5mplwgt.config_chart_text(title='时间序列数据', xlabel='时间', ylabel='')
    timer = QTimer()


    def f():
        n = 300
        pmqt5mplwgt.set_data([i + 1 for i in range(n)],
                             [[randint(0, 30) for i in range(n)], [randint(0, 100) for i in range(n)]],
                             ['Cpu1', 'Cpu2'])


    timer.timeout.connect(f)
    timer.start(33)
    pmqt5mplwgt.show()
    app.exec()
